'use strict';

const Service = require('egg').Service;

class CarService extends Service {
    //添加
    async create(user_id,product_id,num) {
        await this.app.mysql.query('insert into carlist (user_id,product_id,num) values (?,?,?)',[user_id,product_id,num]);
    }
    //修改
    async update(user_id,product_id,num){
        await this.app.mysql.query('update carlist set num=? where user_id=? and product_id=?',[num,user_id,product_id])
    }
    //修改
    async carUpdate(id,num){
        await this.app.mysql.query('update carlist set num=? where id=?',[num,id])
    }
    //删除
    async destroy(id){
        await this.app.mysql.query('delete from carlist where id=?',[id])
    }
    //全部清空
    async delAll(ids){
        await this.app.mysql.query(`delete from carlist where id in (${ids})`)
    }
    //查找购物车列表
    async index(user_id){
        let carlist = await this.app.mysql.query('select * from carlist where user_id=?',[user_id])
        console.log("===carlist",carlist)
        for(let i = 0;i<carlist.length;i++){
            //{num:4,product_id}
            let target = await this.app.mysql.query('select * from productlist where id=?',[carlist[i].product_id])
            let {title,price,pic} = target[0];
            carlist[i] = {num:carlist[i].num,id:carlist[i].id,title,price,pic}
        }
        return carlist
    }

    //查询 是否添加过商品
    async selectProduct(user_id,product_id){
        return this.app.mysql.query('select * from carlist where user_id=? and product_id=?',[user_id,product_id])
    }
}

module.exports = CarService;
